package com.deductive.service.special.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deductive.domain.special.SpecialTableColumn;
import com.deductive.mapper.PgDBMapper;
import com.deductive.mapper.special.SpecialTableColumnMapper;
import com.deductive.service.special.SpecialTableColumnService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 王浩
 * @since 2024-11-06 14:12:51
 */
@Service
public class SpecialTableColumnServiceImpl extends ServiceImpl<SpecialTableColumnMapper, SpecialTableColumn> implements SpecialTableColumnService {

    @Autowired
    private SpecialTableColumnMapper desdTableColumnDao;




    @Autowired
    private PgDBMapper pgDBMapper;




    @Override
    public void insertColumn(String tableName) {
        LambdaQueryWrapper<SpecialTableColumn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpecialTableColumn::getTableName, tableName);
        int delete = desdTableColumnDao.delete(queryWrapper);
        List<JSONObject> columns = pgDBMapper.getColumns(tableName);
        for (JSONObject column : columns) {
            SpecialTableColumn desdTableColumn = new SpecialTableColumn();
            String columnName = column.getString("column_name");
            String newColumnName = columnName.toLowerCase();
            if (!columnName.equals(newColumnName)) {
                pgDBMapper.updateColumn(tableName, columnName, newColumnName);
            }
            LambdaQueryWrapper<SpecialTableColumn> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SpecialTableColumn::getColumnName, newColumnName)
                    .eq(SpecialTableColumn::getTableName, tableName);
            long count = desdTableColumnDao.selectCount(wrapper);
            if (count == 0) {
                desdTableColumn.setColumnName(newColumnName);
                desdTableColumn.setTableName(tableName);
                desdTableColumnDao.insert(desdTableColumn);
            }
        }
    }
}
